package pers.xuyong.strive.shiro.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.web.config.WebIniSecurityManagerFactory;

/**
 * util
 *
 * @author billymac
 * @version 1.0
 * @date 17/3/19  下午8:30
 * @since JDK1.8
 */
public class ShiroUtil {

    //securityManager工厂
    Factory<SecurityManager> factory;

    //SecurityManager实例
    SecurityManager securityManager;

    //subject实体
    Subject subject;

    //私有构造方法
    private ShiroUtil() {}


    /**
     * 获得securityManager实例
     * @return
     */
    public Factory getSecurityManagerFactory() {
        return getSecurityManagerFactory("classpath:shiro-multi-realm.ini");
    }

    public Factory getSecurityManagerFactory(String path) {
        if (factory == null)
            initSecurityManagerFactory(path);
        return factory;
    }

    /**
     * 初始化securityManager工厂
     * 可以对比:WebIniSecurityManagerFactory
     * @param path
     */
    private void initSecurityManagerFactory(String path) {
        if (factory == null)
            factory = new IniSecurityManagerFactory(path);
    }

    /**
     * 获得SecurityManager实例
     * @return
     */
    public SecurityManager getSecurityManagerInstance() {
        if (factory == null)
            getSecurityManagerFactory();
        return factory.getInstance();
    }

    /**
     * 获得shiro主题
     * @return
     */
    public Subject getSubject() {
        if (securityManager == null)
            SecurityUtils.setSecurityManager(getSecurityManagerInstance());
        else
            SecurityUtils.setSecurityManager(securityManager);
        return SecurityUtils.getSubject();

    }

    /**
     * 获得用户token
     * @param username
     * @param password
     * @return
     */
    public UsernamePasswordToken getToken (String username, String password) {
        return new UsernamePasswordToken(username, password);
    }
    

    //实现单例
    private final static  class ShiroUtilIn {
        private final static ShiroUtil shiroUtil = new ShiroUtil();
    }

    /**
     * 获得shiro实例
     * @return
     */
    public static ShiroUtil getInstance() {
        return ShiroUtilIn.shiroUtil;
    }

}
